package com.sky.controller.admin;

import cn.hutool.core.lang.UUID;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = "通用接口")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/common")
public class CommonController {
    private final AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("文件上传{}", file.getOriginalFilename());
        String filePath=null;
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取拓展名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
            //新文件名
            String fileName = UUID.randomUUID() + suffix;
            filePath = aliOssUtil.upload(file.getBytes(), fileName);
        } catch (IOException e) {
            log.error("文件上传失败{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        return Result.success(filePath);
    }
}
